package buaa.leetcode.String;

public class String2Integer_atoi {
	public static int atoi1(String str) {
		if(str.length() < 1){return 0;}
        str = str.trim();
        boolean flag = true;
        int result = 0;
        int start = 0;
        char tmpChar = str.charAt(0);
        if(tmpChar == '+'){
            flag = true;
            start = 1;
        }else if(tmpChar == '-'){
            flag = false;
            start = 1;
        }else{
            start = 0;
        }
        for(int i = start; i < str.length();i++){
            tmpChar = str.charAt(i);
            if(tmpChar < '0' || tmpChar > '9'){
                break;
            }
            if(result > (Integer.MAX_VALUE/10)){
                return flag?Integer.MAX_VALUE:Integer.MIN_VALUE;
            }
            if(result == Integer.MAX_VALUE/10){
                if (tmpChar >= '8' ){return flag?Integer.MAX_VALUE:Integer.MIN_VALUE;}
               // if((tmpChar == '8') && (flag == false)){return Integer.MIN_VALUE;}
                if((tmpChar == '7') && (flag == true)){return Integer.MAX_VALUE;}
            }
            result = result * 10 + (tmpChar - '0');
        
        }
        return flag ? result : (0 - result);
		    }
	public static int atoi2(String str) {
        if(str.length() < 1){return 0;}
        str = str.trim();
        boolean flag = true;
        long result = 0;
        int start = 0;
        char tmpChar = str.charAt(0);
        if(tmpChar == '+'){
            flag = true;
            start = 1;
        }else if(tmpChar == '-'){
            flag = false;
            start = 1;
        }else{
            start = 0;
        }
        for(int i = start; i < str.length();i++){
            tmpChar = str.charAt(i);
            if(tmpChar < '0' || tmpChar > '9'){
                break;
            }
            result = result * 10 + (tmpChar - '0');
        }
        if((result >= Integer.MAX_VALUE) && flag){
        	return Integer.MAX_VALUE;
        }
        if((0-result <= Integer.MIN_VALUE) && (flag==false)){
        	return Integer.MIN_VALUE;
        }
        return (int)(flag ? result : (0 - result));
    }
	public static void main(String[] args){
		System.out.println(atoi1("2147483648"));
	}
}
